import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, ScrollView, Text } from '@tarojs/components'
import { AtInputNumber, AtNoticebar } from 'taro-ui'
import classnames from 'classnames'
import { staticUrl } from '@/utils'
import { connect } from 'react-redux'
import tipsImg from '@/utils/global'
import EmptyView from '@/components/EmptyView'
import { getCartList, updateNumber, getPrice, deleteCart } from '@/api/cart'
import './index.scss'

interface Carts {
  invalidList: {
    id: number
    itemNumber: number
    itemLogo: string
    itemName: string
    itemSubId: number
    itemSubName: string
    itemPrice: number | string
  }[]
  validList: {
    style: any
    id: number
    checked: boolean
    itemNumber: number
    itemLogo: string
    itemName: string
    itemSubId: number
    itemSubName: string
    itemPrice: number | string
    goods: {
      id: number
      laborFee: number | string
    }
  }[]
}

interface State {
  isEdit: boolean
  carts: Carts | null,
  barHeight: number
  delWidth: number
  fix: boolean
  selectAll: boolean
  countPrice: string
  tap: any
}

@connect<any>(({ user }) => ({ user }))
export default class Index extends Component<any> {
  constructor(props) {
    super(props)
    this.state = {
      isEdit: false,
      carts: null,
      barHeight: 0,
      delWidth: 0,
      fix: false,
      selectAll: false,
      countPrice: '0.00',
      tap: {
        startX: 0
      },
    }
  }
  state: State

  UNSAFE_componentWillMount() { }

  componentDidMount() { }

  componentWillUnmount() { }

  componentDidShow() {

      const { user } = this.props
      if (user.userInfo.accessId) {
        this.getCartList()
      } else {
        this.setState({
          carts: {
            invalidList: [],
            validList: []
          }
        })
      }
  }
  componentDidHide() { }

  tapStart(e) {
    if (e.touches.length) {
      const { tap } = this.state
      this.setState({
        tap: {
          ...tap,
          startX: e.touches[0].clientX
        }
      })
    }
  }
  tapMove(e) {
    const { tap, delWidth, carts } = this.state
    if (!carts) return
    const index = e.currentTarget.dataset.index
    if (e.touches.length) {
      const moveX = e.touches[0].clientX
      const diffX = tap.startX - moveX
      let style = {}
      if (diffX <= 0) {
        style = {
          'transform': 'translate3d(0px, 0, 0)'
        }
      } else if (diffX > 0) {
        style = {
          'transform': `translate3d(-${diffX}px, 0, 0)`
        }
        if (diffX >= delWidth) {
          style = {
            'transform': `translate3d(-${delWidth}px, 0, 0)`
          }
        }
      }
      carts.validList[index].style = style
      this.setState({
        carts
      })
    }
  }
  tapEnd(e) {
    const { tap, delWidth, carts } = this.state
    if (!carts) return
    const index = e.currentTarget.dataset.index
    this.clearMove()
    if (e.changedTouches.length == 1) {
      //手指移动结束后触摸点位置的X坐标
      const endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      const diffX = tap.startX - endX;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      const style = diffX > delWidth / 2 ? {
        'transform': `translate3d(-${delWidth}px, 0, 0)`
      } : {
        'transform': 'translate3d(0px, 0, 0)'
      }
      carts.validList[index].style = style
      this.setState({
        carts
      })
    }
  }

  clearMove() {
    const { carts } = this.state
    if (!carts) return
    this.setState({
      carts: {
        ...carts,
        validList: carts.validList.map(v => v.style = '')
      }
    })
  }

  // 滑动删除
  delGood(index: number) {
    const { carts } = this.state
    if (!carts) return
    const validGood = carts.validList[index]
    Taro.showModal({
      content: '您确认删除？',
      cancelText: '取消',
      cancelColor: '#999999',
      confirmText: '删除',
      confirmColor: '#FF3B30',
    }).then(res => {
      if (res.confirm) {
        // console.log(validGood)
        deleteCart({ ids: JSON.stringify([validGood.id]) }).then(() => {
          Taro.showToast({
            icon: 'none',
            title: '删除成功'
          })
          // 刷新购物车数据
          carts.validList.splice(index, 1)
          let count = 0
          for (let valid of carts.validList) {
            if (valid.checked) {
              ++count
            }
          }
          this.setState({
            carts,
            selectAll: count > 0 && count === carts.validList.length
          }, () => this.getPrice())
        })
      }
    })
  }
  // 获取勾选的id
  getIds(mode: string = 'valid') {
    const { carts } = this.state
    if (!carts) return
    if (mode !== 'valid') {
      return carts.invalidList.map(v => v.id)
    }
    return carts.validList.filter(v => v.checked).map(v => v.id)
  }

	// 是否加入了不同门店的购物车商品
  isThoat() {
    const { carts } = this.state
    if (!carts) return
    let arr =  carts.validList.filter(v => v.checked).map(v=>v.storeCode)
		let newArr = [...new Set(arr)]
		return newArr.length > 1 ? true : false
  }
  // 获取dom结构信息
  getDomData=()=> {
			let query = Taro.createSelectorQuery();
			Taro.nextTick(() => {
				query.select('.cartbar-wrap')
				.boundingClientRect((e) => {
					const { height } = e
					this.setState({
						barHeight: height
					})
				})
				.select('.del')
				.boundingClientRect((e) => {
					if (e) {
						const { width } = e
						this.setState({
							delWidth: width
						})
					}
				})
				.exec()
			})
  }
  // 获取购物车列表
  getCartList() {
    getCartList().then(res => {
      const data = res.data.data
      if (data.validList.length) {
        // 初始化勾选状态
        data.validList.map(v => {
          v.checked = false
          v.style = ''
        })
      }
      this.setState({
        isEdit: false,
        carts: data,
        selectAll: false,
        countPrice: '0.00'
      }, () => this.getDomData())
    })
  }
  // 获取购物车勾选的价格
  getPrice() {
    const ids = JSON.stringify(this.getIds())
    getPrice({
      ids
    }).then(res => {
      const data = res.data.data
      this.setState({
        countPrice: data.totalPrice
      })
    })
  }
  // 修改商品数量
  handleChange(e, val) {
    const { id, goods } = e
    const num = Number(val)
    const { carts } = this.state
    if (goods.maxNumber != 0 && num > goods.maxNumber) {
      return Taro.showToast({
        title: '超出相同订单最多可销售次数',
        icon: 'none'
      })
    }
    if (!carts) return
    const validList = carts.validList.map(v => {
      if (v.id === id) {
        v.itemNumber = num
      }
      return v
    })
    this.setState({
      carts: {
        ...carts,
        validList
      }
    }, () => {
      updateNumber({
        id,
        number: num
      }).then(res => {
        this.getPrice()
      })
    })
  }
  // 编辑
  editGoods(e) {
    const { isEdit } = this.state
    this.setState({
      isEdit: !isEdit
    })
  }
  // 下单与删除
  handleGoods() {
    const ids = this.getIds()
    if (!ids || !ids.length) {
			Taro.showToast({
				icon: 'none',
				title: '请先选择商品再下单！'
			})
			return
		}
    const { isEdit, carts } = this.state
    if (!carts) return
    if (isEdit) {
      Taro.showModal({
        content: '您确认删除？',
        cancelText: '取消',
        cancelColor: '#999999',
        confirmText: '删除',
        confirmColor: '#FF3B30',
      }).then(res => {
        if (res.confirm) {
          // 删除
          deleteCart({ ids: JSON.stringify(ids) }).then(() => {
            Taro.showToast({
              icon: 'none',
              title: '删除成功'
            })
            // 刷新购物车数据
            this.setState({
              carts: {
                ...carts,
                validList: carts.validList.filter(v => ids.some(id => id !== v.id))
              }
            })
          })
        }
      })
    } else {
      // 下单
      if (ids.length) {
				let isThoat = this.isThoat() ? 1 : ''
        Taro.navigateTo({
          url: `/pages/order/index/index?cartIds=${JSON.stringify(ids)}&isThoat=${isThoat}`
        })
      } else {
        Taro.showToast({
          icon: 'none',
          title: '请勾选商品',
          duration: 2000
        })
      }
    }
  }
  // 勾选
  handleCheck(e) {
    const { value } = e.currentTarget.dataset
    let state: any = {}
    const { carts } = this.state
    if (!carts) return
    if (!carts.validList.length) return
    if (value === 'all') {
      const { selectAll } = this.state
      state = {
        selectAll: !selectAll
      }
      if (state.selectAll) {
        state.carts = {
          ...carts,
          validList: carts.validList.map(v => {
            v.checked = true
            return v
          })
        }
      } else {
        state.carts = {
          ...carts,
          validList: carts.validList.map(v => {
            v.checked = false
            return v
          })
        }
      }
    } else {
      let count = 0
      state.carts = {
        ...carts,
        validList: carts.validList.map(v => {
          if (v.id === Number(value)) {
            v.checked = !v.checked
          }
          if (v.checked) {
            ++count
          }
          return v
        })
      }
      state.selectAll = count > 0 && count === carts.validList.length
    }
    this.setState(state, () => this.getPrice())
  }
  // 滚动设置浮动
  changeScroll(e) {
    const { barHeight } = this.state
    const { scrollTop } = e.detail
    if (scrollTop >= barHeight) {
      this.setState({
        fix: true
      })
    } else {
      this.setState({
        fix: false
      })
    }
  }
  // 清楚所有失效商品
  clearAll() {
    const ids = this.getIds('invalid')
    const { carts } = this.state
    Taro.showModal({
      content: '您确认删除？',
      cancelText: '取消',
      cancelColor: '#999999',
      confirmText: '删除',
      confirmColor: '#FF3B30',
    }).then(res => {
      if (res.confirm) {
        // 删除
        deleteCart({ ids: JSON.stringify(ids) }).then(() => {
          Taro.showToast({
            icon: 'none',
            title: '删除成功'
          })
          // 刷新购物车数据
          this.setState({
            carts: {
              ...carts,
              invalidList: []
            }
          })
        })
      }
    })
  }

  goodsView() {
    const { carts } = this.state
    if (!carts) return
    return carts.validList.length > 0 || carts.invalidList.length > 0 ? (
      <View className='cart-bd'>
        <View className='valid'>
          {
            carts.validList.map((v, idx) => {
              return (
                <View className='cart-item-li' key={v.id} data-index={idx} style={v.style} onTouchMove={this.tapMove.bind(this)} onTouchEnd={this.tapEnd.bind(this)} onTouchStart={this.tapStart.bind(this)} >
										<View className='del' onClick={(e) => this.delGood(idx, e)}></View>
										<View data-value={v.id} onClick={this.handleCheck.bind(this)} className={classnames('check', v.checked && 'act')}>
											<View className='at-icon at-icon-check'></View>
										</View>
										<Image src={v.itemLogo ? v.itemLogo : tipsImg} className='good-img'></Image>
										<View className='content'>
											<View className='content-name'>{v.itemName}</View>
											<View className='content-sku' data-id={v.itemSubId}>{v.itemSubName}</View>
											<View className='content-sname'>门店：{v.storeName}</View>
											<View className='number-group'>
												<View className='price'>￥{v.itemPrice}</View>
												<AtInputNumber
													type='number'
													min={1}
													step={1}
													value={v.itemNumber}
													onChange={(e) => this.handleChange(v, e)}
												/>
											</View>
											{v.goods && v.goods.laborFee > 0 && <View className='text'>另需工时费：￥{v.goods.laborFee}</View>}
										</View>
								</View>
              )
            })
          }
        </View>
        {
          carts.invalidList.length > 0 &&
          (
            <View className='invalid'>
              <AtNoticebar className='notice' icon='alert-circle'>以下商品已失效 <Text onClick={() => this.clearAll()} className='clear-all'>马上清空</Text></AtNoticebar>
              {
                carts.invalidList.map(v => {
                  return (
                    <View key={v.id} className='cart-item-li'>
												<Image src={v.itemLogo ? v.itemLogo : tipsImg} className='good-img'></Image>
												<View className='content'>
													<View className='content-name'>{v.itemName}</View>
													<View className='content-sku' data-id={v.itemSubId}>{v.itemSubName}</View>
													<View className='content-sname'>门店：{v.storeName}</View>
													<View className='number-group'>
														{/* <View className='price'>￥{v.itemPrice}</View> */}
													</View>
												</View>
										</View>
                  )
                })
              }
            </View>
          )
        }
      </View>
    ) : (<EmptyView title='购物车空空如也' />)
  }

  render() {
    const { carts, isEdit, fix, selectAll, countPrice } = this.state
    return carts && (
      <View className={classnames('cart-index', fix && 'fix-top')}>
        <ScrollView scrollY onScroll={(e) => this.changeScroll(e)} className='cart-bd-cont'>
          <View className='cart-hd'>
            <View className='cartbar-wrap'>
              <Image src={staticUrl('/img/cart/cart-bar.jpg')} className='bar'></Image>
              <View className='bar-msg'>
                <View className='name'>购物车</View>
                <View className='num'>共{carts.validList.length}件商品</View>
              </View>
            </View>
            <View className='cart-title'>
              商品列表
                <View onClick={this.editGoods.bind(this)} className={classnames('cart-handle-btn', isEdit && 'done')}>{isEdit ? '完成' : '编辑'}</View>
            </View>
          </View>
          {this.goodsView()}
        </ScrollView>
        <View className='cart-ft'>
          <View data-value='all' onClick={this.handleCheck.bind(this)} className={classnames('check', selectAll && 'act')}>
            <View className='at-icon at-icon-check'></View>
          </View>
          <View className='count-price'>
            合计：<View className='price'>￥{countPrice}</View><View onClick={(e) => this.handleGoods(e)} className={classnames({'handle-btn':true,'del':isEdit})}>{isEdit ? '删除' : '去下单'}</View>
          </View>
        </View>
      </View>
    )
  }
}
